package com.spring.framework.config.autowired.model;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * 注解 @Qualifier可以设置一个value值，该值就是一个bean的名字。@Qualifier只有被标注在属性或者方法/构造器的参数
 * 前面才会生效。基于XML的配置中，我们也可以使用标签完成类似的功能。
 *
 * @author xuweizhi
 * @since 2020/12/15 11:23
 */
@Component
public class AutowiredQualifierDemo {

	/**
	 * Qualifier指定bean name为qualifierDemoB的bean注入进来
	 */
	@Autowired
	@Qualifier("qualifierDemoA")
	private QualifierDemoA qualifierDemo;


	public void setQualifierDemo(QualifierDemoA qualifierDemo) {
		this.qualifierDemo = qualifierDemo;
	}

	/**
	 * 标注在参数前面才会生效
	 */
	@Bean
	public AutowiredQualifierDemo getAutowiredQualifierDemo(@Qualifier("qualifierDemoB") QualifierDemoA qualifierDemo) {
		System.out.println("qualifierDemo--------" + qualifierDemo);
		AutowiredQualifierDemo autowiredQualifierDemo = new AutowiredQualifierDemo();
		//虽然现在设置的是qualifierDemoB对象，但是交给容器之后会被替换，相当于又被注入了一次qualifierDemoA
		autowiredQualifierDemo.setQualifierDemo(qualifierDemo);
		return autowiredQualifierDemo;
	}

	@Component("qualifierDemoA")
	public static class QualifierDemoA {
		public QualifierDemoA() {
			System.out.println("QualifierDemoA：" + this);
		}
	}

	@Component("qualifierDemoB")
	public static class QualifierDemoB extends QualifierDemoA {
		public QualifierDemoB() {
			System.out.println("QualifierDemoB：" + this);
		}
	}

	@Override
	public String toString() {
		return "AutowiredQualifierDemo{" +
				"nullableDemo=" + qualifierDemo +
				'}';
	}
}
